package com.sofwin.configer;

import com.sofwin.pojo.SysUser;
import com.sofwin.service.ResourceService;
import com.sofwin.service.UserService;
import lombok.Data;
import org.apache.shiro.authc.*;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.crypto.hash.Md5Hash;
import org.apache.shiro.realm.AuthenticatingRealm;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.realm.Realm;
import org.apache.shiro.realm.SimpleAccountRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.apache.shiro.util.ByteSource;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.HashSet;
import java.util.List;
import java.util.Set;

/**
 * @packageName: com.sofwin.configer
 * @author: andyliu
 * @date: 2022/5/7 10:12
 * @email 115176513@qq.com
 * @description: TODO
 */
public class MyRealm  extends AuthorizingRealm {
    @Autowired
    private UserService userService;
    @Autowired
    private ResourceService resourceService;

    /**
     * 授权
     * 1. 以角色授权
     * 2. 细粒度授权
     * @param principalCollection
     * @return
     */
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
       // 获取当前登录的唯一的用户名
        String loginName = principalCollection.getPrimaryPrincipal().toString();
        SysUser user = userService.checkLogin(loginName);
       // 定义授权信息
        SimpleAuthorizationInfo info = new SimpleAuthorizationInfo();
        // 一个用户只能有一个角色
        // 一个用户可以有多个角色，角色的集合设置
        Set<String> roles = new HashSet<>();
        roles.add(user.getRoleId().toString());
        info.setRoles(roles);
        // 当前角色所拥有的的所有按钮的permission
        List<String> permissions = resourceService.queryPermissionsByRoleId(user.getRoleId());
        // 设置细粒度的权限（按钮级别）
        info.addStringPermissions(permissions);
        return info;
    }

    /**
     * 认证
     * @param token
     * @return
     * @throws AuthenticationException
     */
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {
        UsernamePasswordToken mtoken = (UsernamePasswordToken) token;
        String loginName = mtoken.getUsername();
        SysUser user = userService.checkLogin(loginName);
        // 通过用户名来查询用户信息
        if(user==null){
            throw new UnknownAccountException();
        }
        // 进行密码校验的  用户名 密码（数据库中的密码）   用户的密码存在token
        return new SimpleAuthenticationInfo(user.getLoginName(),user.getPassword(), ByteSource.Util.bytes(user.getSalt()),getName());
    }
}
